from flask import abort
from flask import current_app
from flask import g
from flask import make_response, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


@profile_blue.route('/other_news_list')
def other_news_list():
    p = request.args.get('p',1)
    user_id = request.args.get('user_id')

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库失败')

    if not user:
        return jsonify(errno=RET.DATAERR,errmsg='用户不存在')

    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginates = News.query.filter(News.user_id == user.id).paginate(p,constants.OTHER_NEWS_PAGE_MAX_COUNT,False)
        news_li = paginates.items
        current_page = paginates.page
        total_page = paginates.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_review_dict())

    data = {
        'news_list':news_dict_li,
        'current_page':current_page,
        'total_page':total_page
    }

    return jsonify(errno=RET.OK,errmsg='OK',data=data)

@profile_blue.route('/other_info')
@user_login_data
def other_info():
    # http://127.0.0.1:5000/user/other_info?user_id=6
    user = g.user
    user_id = request.args.get('user_id')
    try:
        user_id = int(user_id)
    except Exception as e:
        current_app.logger.error(e)

    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    is_followed = False
    if user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {
        'user_info':user.to_dict(),
        'other_info':other.to_dict(),
        'is_followed':is_followed
    }
    return render_template('news/other.html', data=data)


@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


@profile_blue.route('/news_list')
@user_login_data
def news_list():

    # 获取页数 window.location.href = '/user/news_list?p=' + current
    page = request.args.get('p', 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_model_list = []
    current_page = 1
    total_page = 1

    try:
        paginates = News.query.filter(News.user_id == g.user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_model_list = paginates.items
        current_page = paginates.page
        total_page = paginates.pages

    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        category_dict_li.pop(0)
        data = {
            'categories': category_dict_li
        }

        return render_template('news/user_news_release.html', data=data)

    # POST请求
    # 获取数据
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 判断完整性
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 把图片上传到七牛云
    try:
        index_image_data = index_image.read()
        image_file_name = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
    news.category_id = category_id

    news.user_id = g.user.id

    # 还需要设置一个审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='保存到数据库失败')

    return jsonify(errno=RET.OK, errmsg='ok')


@profile_blue.route('/collection')
@user_login_data
def user_collection():

    # 获取参数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 获取分页数据
    user = g.user
    collections = []
    current_page = 1
    total_page = 1

    try:
        paginates = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS,False)
        # 分页数据
        collections = paginates.items

        # 当前页数
        current_page = paginates.page

        # 总页数
        total_page = paginates.pages

    except Exception as e:
        current_app.logger.error(e)

    collections_dict_li = []
    for news in collections:
        collections_dict_li.append(news.to_dict())

    data = {
        'current_page':current_page,
        'total_page':total_page,
        'collections':collections_dict_li
    }

    return render_template('news/user_collection.html', data=data)


@profile_blue.route('/pass_info', methods=['POST', 'GET'])
@user_login_data
def pass_info():

    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    #POST请求
    user = g.user
    # 获取当前密码  进行匹配
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg='原密码输入错误')

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg='修改密码成功')


@profile_blue.route('/pic_info', methods=['POST', 'GET'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)

    # 获取头像文件
    try:
        image_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 上传到七牛运
    try:
        avatar_file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
    # 数据库保存文件名
    user.avatar_url = avatar_file_name
    # 返回图像的url地址给前端
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_file_name})


@profile_blue.route('/base_info', methods=['POST', 'GET'])
@user_login_data
def base_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    #POST请求
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    if gender not in (['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新   很重要容易忽略
    session["nick_name"] = nick_name

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blue.route('/info')
@user_login_data
def user_info():
    # 判断用户是否登录
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user':g.user.to_dict()
    }
    return render_template('news/user.html', data=data)


